<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入编号或者名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表v-loading="listLoading"
    :data="systemDictionaryTypes" -表格数据
    v-loading="listLoading" -> 加载圈
    @selection-change="handleSelectionChange" -> 批量删除
    highlight-current-row  -> 选择一行数据，变亮
    -->
    <el-table :data="systemDictionaryTypes" v-loading="listLoading"
              @selection-change="handleSelectionChange" highlight-current-row
              style="width: 100%;" :row-key="SpreadPages" @row-dblclick="handleDetail">
      <!--多选框-->
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" width="70" label="序号">
      </el-table-column>

      <el-table-column prop="name" label="类型名称" width="120"/>
      <el-table-column prop="sn" label="类型编号" width="200"/>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--点击查看抽屉-->
    <el-drawer
        title="数据字典明细"
        :visible.sync="drawer"
        :direction="direction"
        :append-to-body="true"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true">
          <el-form-item>
            <el-input v-model="keywordD" placeholder="请输入部门编号或者名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" v-on:click="keywordQueryD">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAddD()">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-table :data="systemDictionaryDetails" v-loading="listLoadingD"
                @selection-change="handleSelectionChangeDetail" highlight-current-row
                style="width: 100%;" :row-key="SpreadPagesDetails">
        <!--多选框-->
        <el-table-column type="selection" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" width="70" label="序号">
        </el-table-column>

        <el-table-column prop="name" label="类型名称" width="120"/>
        <el-table-column prop="dictionaryTypeSn" label="类型编号" width="150"/>

        <el-table-column label="操作">
          <template scope="scope">
            <el-button size="small" @click="handleEditD(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelD(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-button type="danger" :disabled="this.selsdetail.length === 0" @click="handlePatchDelDetail">批量删除</el-button>
        <el-pagination @size-change="handleSizeChangeD"
                       @current-change="handleCurrentChangeD" :current-page="currentPageD"
                       :page-sizes="[5, 10, 15]" :page-size="pageSizeD" layout="total, sizes, prev, pager, next, jumper"
                       background
                       :total="totals" style="float:right;">
        </el-pagination>
      </el-col>

      <!--添加或修改界面-->
      <el-dialog :title="title" :visible.sync="saveFormVisibleD" :close-on-click-modal="false"
                 :append-to-body="true" @open="handleDialogOpenD">
        <el-form :model="saveFormD" label-width="80px" :rules="saveFormRulesD" ref="saveFormD">

          <el-form-item label="类型名称" prop="name">
            <el-input v-model="saveFormD.name" auto-complete="off"@focus="clearCurrentValidateD('name')"/>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="saveFormVisibleD = false">取消</el-button>
          <el-button type="primary" @click.native="saveSubmitD">提交</el-button>
        </div>
      </el-dialog>

    </el-drawer>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                     background
                     :total="totals" style="float:right;">
      </el-pagination>
    </el-col>
    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" @open="handleDialogOpen">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">

        <el-form-item label="类型名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"@focus="clearCurrentValidate('name')"/>
        </el-form-item>

        <el-form-item label="类型名称" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off" @focus="clearCurrentValidate('sn')"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

import {Row} from "element-ui";

export default {
  computed: {
    Row() {
      return Row
    }
  },
  data() {
    return {
      //1.分页查询相关数据
      totals: 0,//总记录条数
      currentPage: 1,//当前页,要传递到后台的
      pageSize: 5, //每页显示多少条
      systemDictionaryTypes: [], //当前页数据


      listLoading: false, //加载圈

      title: '',

      //2.高级查询相关数据
      keyword: '',
      //4.批量删除相关数据
      sels: [], //存储多选记录

      //5.添加和修改相关数据
      saveFormVisible: false,

      drawer: false, //抽屉
      direction: 'rtl', //Drawer 抽屉打开的方向rtl / ltr / ttb / btt	默认rtl

      saveForm: {
        id: null,
        name: '',
        types_id:null,
      },
      //添加和修改校验规则-表单项校验
      saveFormRules: {
        name: [
          {required: true, message: '请输入类型名称', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入类型编号', trigger: 'blur'}
        ],
      },

      //以下都是抽屉中的属性
      systemDictionaryDetails:[],
      totalsDetail:0,
      currentPageD: 1,//当前页,要传递到后台的
      pageSizeD: 5, //每页显示多少条
      keywordD:'',
      types_id:null,
      saveFormVisibleD: false,
      listLoadingD:false,
      selsdetail:[],
      saveFormD:{
        id: null,
        name: '',
        types_id:null,
      },
      saveFormRulesD: {
        name: [
          {required: true, message: '请输入类型名称', trigger: 'blur'}
        ],
      },
    }
  },
  methods: {
    //跨页操作
    SpreadPages(row) {
      return row.id
    },
    SpreadPagesDetails(row) {
      return row.id
    },
    //1.分页查询相关方法
    //1.1.获取列表数据
    getTableData() {
      this.listLoading = true //开启加载圈
      var params = {
        "currentPage": this.currentPage, //点击的当前第几页
        "pageSize": this.pageSize,   //当前页需要显示多少条数据
        "keyword": this.keyword    //模糊查询 ->关键字
      }
      this.$http.post("/systemDictionaryType", params).then(res => {
        //接收参数添加到表格中(systemDictionaryTypes),request.data ->固定写法
        this.systemDictionaryTypes = res.data.list
        this.totals = res.data.totals
        this.listLoading = false //关闭加载圈
      })
    },

    getDictionaryDetails() {
      this.listLoadingD = true //开启加载圈
      var params = {
        "currentPage": this.currentPageD, //点击的当前第几页
        "pageSize": this.pageSizeD,   //当前页需要显示多少条数据
        "keyword": this.keywordD,   //模糊查询 ->关键字
        "typeId":this.types_id
      }
      this.$http.post("/systemDictionaryDetail", params).then(res => {
        this.systemDictionaryDetails = res.data.list
        this.totals = res.data.totals
        this.listLoadingD = false //关闭加载圈
      })
    },
    //1.2.选择第几页时触发
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage //1 -> 2
      this.getTableData()
    },
    //1.3.选择每页显示记录条数时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getTableData()
    },

    //2.高级查询相关方法
    keywordQuery() {
      this.currentPage = 1; //从第一页开始查询
      this.getTableData();
    },

    //3.删除相关方法
    //row -> 当前行对象 获取一行数据
    handleDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/systemDictionaryType/" + row.id,).then(res => {
          if (res.data.success) {
            //处理当前页->算总页数 Math.ceil() (向上取整，往最大了取值)
            let totalPage = Math.ceil(this.totals/this.pageSize);
            //当删除最后一页的最后一条数据，并且不是第一页，就让当前页-1
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage = this.currentPage - 1;
            }
            this.sels=[]
            this.$message.success("操作删除成功")
            this.getTableData()
          } else {
            this.$message.error("服务器异常，删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消删除")
      });
    },

    //4.批量删除相关方法
    //4.1.选项改变时触发
    handleSelectionChange(val) {
      this.sels = val
    },
    //4.2.批量删除
    handlePatchDel() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.sels.map(obj => obj.id)//获取批量删除对象的id，组成数组。
        this.$http.patch("/systemDictionaryType", ids).then(res => {
          if (res.data.success) {

            //计算总页数  Math.ceil() (向上取整，往最大了取值) Math.floor() (向下取整，往最小了取值)
            if (ids.length >= this.systemDictionaryTypes.length && this.currentPage!==1) { //页数合理化
              let number = Math.ceil(this.totals / this.pageSize) - (Math.floor((ids.length - this.totals%this.pageSize) / this.pageSize) + 1);
              if (number < this.currentPage) {
                this.currentPage = number
              }
            }
            this.sels = []
            this.$message.success("操作批量删除成功")
            this.getTableData()
          } else {
            this.$message.error("服务器异常，批量删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消批量删除")
      });
    },


    //以下都是抽屉中的方法
    handleSelectionChangeDetail(val) {
      this.selsdetail = val
    },
    handlePatchDelDetail() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.selsdetail.map(obj => obj.id)//获取批量删除对象的id，组成数组。
        this.$http.patch("/systemDictionaryDetail", ids).then(res => {
          if (res.data.success) {

            //计算总页数  Math.ceil() (向上取整，往最大了取值) Math.floor() (向下取整，往最小了取值)
            if (ids.length >= this.systemDictionaryDetails.length && this.currentPageD!==1) { //页数合理化
              let number = Math.ceil(this.totalsDetail / this.pageSizeD) - (Math.floor((ids.length - this.totalsDetail%this.pageSizeD) / this.pageSizeD) + 1);
              if (number < this.currentPageD) {
                this.currentPageD = number
              }
            }
            this.selsdetail=[]
            this.$message.success("操作批量删除成功")
            this.getDictionaryDetails()
          } else {
            this.$message.error("服务器异常，批量删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消批量删除")
      });
    },
    handleCurrentChangeD(currentPageD) {
      this.currentPageD = currentPageD //1 -> 2
      this.getDictionaryDetails()
    },
    handleSizeChangeD(pageSizeD) {
      this.pageSizeD = pageSizeD
      this.getDictionaryDetails()
    },
    keywordQueryD() {
      this.currentPageD = 1; //从第一页开始查询
      this.getDictionaryDetails()
    },
    handleDelD(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/systemDictionaryDetail/" + row.id,).then(res => {
          if (res.data.success) {
            //处理当前页->算总页数 Math.ceil() (向上取整，往最大了取值)
            let totalPage = Math.ceil(this.totalsDetail/this.pageSizeD);
            //当删除最后一页的最后一条数据，并且不是第一页，就让当前页-1
            if(this.currentPageD==totalPage && (this.totalsDetail-1)%this.pageSizeD==0 && this.currentPageD!=1){
              this.currentPageD = this.currentPageD - 1;
            }
            this.$message.success("操作删除成功")
            this.getDictionaryDetails()
          } else {
            this.$message.error("服务器异常，删除失败")
          }
        }).catch(res => {
          this.$message.error("网络异常，请查看您的网络")
        })
      }).catch(() => {
        this.$message.error("已取消删除")
      });
    },
    handleAddD() {
      this.title = "添加数据"
      this.saveFormVisibleD = true //打开模态框
      this.saveFormD = {
        id: null,
        name: '',
        typesId:this.types_id
      }

    },
    handleEditD(row) {
      this.title = "编辑数据"
      this.saveFormVisibleD = true //打开模态框
      this.saveFormD = Object.assign({}, row)
      this.saveFormD.types_id = this.types_id
    },
    saveSubmitD() {
      //所有表单项校验通过才能提交，只要员工表单项校验不通过就不能提交，-所有表单项校验通过返回true
      this.$refs.saveFormD.validate((valid) => {
        if (valid) {
          this.$http.put("/systemDictionaryDetail", this.saveFormD).then(res => {
            if (res.data.success) {
              this.$message.success("操作" + this.title + "成功")
              this.getDictionaryDetails()
              this.saveFormVisibleD = false
            } else {
              this.$message.error("服务器异常" + this.title + "未成功")
              this.saveFormVisibleD = false
            }
          }).catch(res => {
            this.$message.error("网络异常，请查看您的网络")
          })
        } else {
          this.$message.error("您有必须填写的数据未填写")
        }
      })
    },
    //1.表单弹出时：清除校验规则
    handleDialogOpenD(){
      if (this.$refs.saveFormD) {
        this.$refs.saveFormD.clearValidate();
      }
    },
    //2.获得焦点清除当前校验
    clearCurrentValidateD(field){
      this.$refs.saveFormD.clearValidate(field);
    },
    //点击查看-抽屉事件
    handleDetail(row){
      this.types_id = row.id
      this.getDictionaryDetails()
      this.keywordD="",
          this.drawer = true; //打开抽屉
    },
    //关闭抽屉事件
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },



    //5.添加和修改相关方法
    //5.1.点击添加弹出对话框
    handleAdd() {
      this.title = "添加数据"
      this.saveFormVisible = true //打开模态框
      this.saveForm = {
        id: null,
        name: '',
        types_id:null,
      }
    },
    //5.2.点击修改弹出对话框
    handleEdit(row) {
      this.title = "编辑数据"
      this.saveFormVisible = true //打开模态框
      this.saveForm = Object.assign({}, row)

    },
    //5.3.提交表单数据操作数据库
    saveSubmit() {
      //所有表单项校验通过才能提交，只要员工表单项校验不通过就不能提交，-所有表单项校验通过返回true
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$http.put("/systemDictionaryType", this.saveForm).then(res => {
            if (res.data.success) {
              this.$message.success("操作" + this.title + "成功")
              this.getTableData()
              this.saveFormVisible = false
            } else {
              this.$message.error("服务器异常" + this.title + "未成功")
              this.saveFormVisible = false
            }
          }).catch(res => {
            this.$message.error("网络异常，请查看您的网络")
          })
        } else {
          this.$message.error("您有必须填写的数据未填写")
        }
      })
    },

    //1.表单弹出时：清除校验规则
    handleDialogOpen(){
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
    //2.获得焦点清除当前校验
    clearCurrentValidate(field){
      this.$refs.saveForm.clearValidate(field);
    },

  },
  mounted() {
    this.getTableData();
  }
}

</script>

<style scoped></style>
